package com.tas.zuulway;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;

public class TokenFillter extends ZuulFilter {
    @Override
    public String filterType() {
        //请求被路由之前
        return "pre";
        //请求路由之前
        //return "post";

    }

    /*执行过滤器的顺序，如果有多个过滤器*/
    @Override
    public int filterOrder() {
        return 1;
    }

    /*是否启用过滤器*/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /*具体的过滤器方法*/
    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取请求
        HttpServletRequest request = ctx.getRequest();
        Object accessToken  = request.getParameter("accessToken");
        if (accessToken == null){
            //通过设置此项拒接请求
            ctx.setSendZuulResponse(false);
            //设置返回状态码
            ctx.setResponseStatusCode(401);
            //设置返回的body内容
            String body = "没有accessToken";
            ctx.setResponseBody(body);
            return null;
        }
        return null;
    }
}
